package com.nai365.nart.product.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * rabbitmq 配置类
 */
@Configuration
public class RabiitMQConfig {

	@Primary
	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
		final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
		rabbitTemplate.setMessageConverter(messageConverter());
		return rabbitTemplate;
	}

	@Bean
	public MessageConverter messageConverter() {
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		om.registerModule(new JavaTimeModule());
		return new Jackson2JsonMessageConverter(om);
	}


	@Bean("chianQueue")
	public Queue chianQueue() {

		return QueueBuilder.durable("chianQueue").build();
	}

	@Bean("chianQueueExchange")
	DirectExchange chianQueueExchange() {

		return ExchangeBuilder.directExchange("chianQueueExchange").build();
	}

	@Bean("chianQueueBind")
	Binding bindingExchange(@Qualifier("chianQueue") Queue chianQueue, @Qualifier("chianQueueExchange") DirectExchange chianQueueExchange) {
		return BindingBuilder.bind(chianQueue).to(chianQueueExchange).with("chian");

	}
}